package com.oneonefive.trainticketsystem.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oneonefive.trainticketsystem.mapper.RefundMapper;
import com.oneonefive.trainticketsystem.mapper.SaleMapper;
import com.oneonefive.trainticketsystem.mapper.TicketMapper;
import com.oneonefive.trainticketsystem.pojo.Ticket;
import com.oneonefive.trainticketsystem.pojo.Train;
import com.oneonefive.trainticketsystem.service.TicketService;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Service
public class TicketServiceImpl extends ServiceImpl<TicketMapper, Ticket>
        implements TicketService {
    final
    SaleMapper saleMapper;
    final
    RefundMapper refundMapper;
    final
    TicketMapper ticketMapper;

    public TicketServiceImpl(TicketMapper ticketMapper, SaleMapper saleMapper, RefundMapper refundMapperMapper) {
        this.ticketMapper = ticketMapper;
        this.saleMapper = saleMapper;
        this.refundMapper = refundMapperMapper;
    }

    @Override
    public List<Ticket> selectTicByTrainId(Integer ticketId, Integer trainId, String coachNo, String seatNo, Integer sold, Integer page) {
        return ticketMapper.selectTicketByTrainId(ticketId, trainId, coachNo, seatNo, sold, (page - 1) * 10);
    }

    @Override
    public int getTicRowCount(Integer ticketId, Integer trainId, String coachNo, String seatNo, Integer sold) {
        return ticketMapper.getTicRowCount(ticketId, trainId, coachNo, seatNo, sold);
    }

    @Override
    public boolean insertTic(int ticketId, int trainId, String coach_no, String seat_no, Integer sold) {
        if (sold == null) sold = 0;
        Train train = new Train(trainId);
        Ticket ticket = new Ticket(ticketId, train, coach_no, seat_no, sold);
        return ticketMapper.insertTicket(ticket);
    }

    @Override
    public boolean soldTic(int ticketId, int userId) {
        Date date = new Date();
        saleMapper.insertSale(null, ticketId, new Timestamp(date.getTime()), userId);
        return ticketMapper.soldTic(ticketId);
    }

    @Override
    public boolean refundTic(int ticketId, int userId) {
        Date date = new Date();
        refundMapper.insertRefund(null, ticketId, new Timestamp(date.getTime()), userId);
        saleMapper.deleteByTicketId(ticketId);
        return ticketMapper.refundTic(ticketId);
    }
}




